<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称" prop="RoleName">
      <el-input v-model="ruleForm.RoleName" />
    </el-form-item>
    <el-form-item label="权限" >
      <el-select-v2
        v-model="ruleForm.PermissionId"
        placeholder="Activity count"
        :options="ShowPermission"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">清空</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'

interface RuleForm {
  RoleName: string
  PermissionId:number
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  RoleName: '',
  PermissionId:0
})

const ShowPermission=ref<any[]>([]);

const GetPermission=()=>{
  axios({
    url:"http://localhost:5028/api/Management/GetPermissionItem",
    method:"get"
  })
  .then(res=>{
    console.log(res);
    if(res.data.Code==200){
      ShowPermission.value=res.data.Result
      var item=ref({
        value:0,
        label:"请选择"
      })
      ShowPermission.value.push(item.value);
    }
  })
}

onMounted(()=>{
  GetPermission();
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  RoleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  PermissionId: [
    { required: true , trigger: 'blur', validator(rule, value, callback) {
      if (value == 0) {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }, },
    
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      axios({
        url:"http://localhost:5117/api/Operate/InsertRole",
        method:"post",
        data:ruleForm
      })
      .then(res=>{
        console.log(res);
        if(res.data.Code==300){
          ElMessage.success("角色添加成功");
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))
</script>
